package com.chen.filter;

import com.chen.pojo.User;
import com.chen.util.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //从session中得到用户
        User user = (User) request.getSession().getAttribute(Constant.USER_SESSION);
        if (user==null){
            //如果用户不存在则直接重定向到错误页面
            response.sendRedirect("/error.jsp");
        }else{
            //如果用户存在则继续过滤直到传给对应的servlet
            filterChain.doFilter(request,response);
        }
    }
}
